const App = getApp();
const TEMPLATE_ID_BALANCE_CHNAGE = "vmEFBaRcFyMK42ZmaK64u5Ou7QbAlTO45GxvB0YE4jw";
const TEMPLATE_ID_ORDER_PAY = "_gbU4La87TZuPSWqkZIZ7Qkht8XpDSLxPWf86F3-FbE";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLogin: false,
        userInfo: {},
        orderCount: {},
        orderPaySubscripted: false,
        notice_order_pay: "点击开启",
        balanceChangeSubscripted: false,
        notice_balance_change: "点击开启",
        notices: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let _this = this
        this.setData({notices: _this.defaultNotices()})
        wx.getSetting({
            withSubscriptions: true,
            success(res) {
                var itemSettings = res.subscriptionsSetting.itemSettings;
                console.log(res)
                if (itemSettings) {
                    for (let templateId in itemSettings) {
                        if (itemSettings[templateId] === 'accept') {
                           _this.setOpen(templateId)
                        }
                    }
                }
            }
        })
    },

    defaultNotices() {
        let notices = {}
        notices[TEMPLATE_ID_BALANCE_CHNAGE] = {
            title: "余额变动提醒",
            opened: false
        };
        notices[TEMPLATE_ID_ORDER_PAY] = {
            title: "订单支付成功通知",
            opened: false
        };
        return notices;
    },

    setOpen(templateId){
        console.log("set open")
        this.setData({
            ["notices."+templateId+".opened"]: true
        });
    },

    /**
     * 跳转到登录页
     */
    onLogin() {
        wx.navigateTo({
            url: '../login/login',
        });
    },

    /**
     * 验证是否已登录
     */
    onCheckLogin() {
        let _this = this;
        if (!_this.data.isLogin) {
            App.showError('很抱歉，您还没有登录');
            return false;
        }
        return true;
    },
    openNotice(event) {
        let templateId = event.currentTarget.dataset.templateid
        console.log(event)
        let _this = this
        if (wx.requestSubscribeMessage) {
            if (!this.data.orderPaySubscripted) {
                wx.requestSubscribeMessage({
                    tmplIds: [templateId],
                    success(res) {
                        console.log(res)
                        _this.setOpen(templateId)
                    }
                })
            }

        } else {
            wx.showModal({
                title: "提示",
                content: "当前微信版本过低，无法使用该功能，请升级到最新的微信版本后重试"
            })
        }
    }
})